# -*- coding:utf-8 -*-

"""
商家黑名单Controller
"""

from fastapi import APIRouter, Depends
from starlette.requests import Request
from sqlalchemy.ext.asyncio import AsyncSession

from config.get_db import get_db
from config.enums import BusinessType
from module_admin.annotation.log_annotation import Log
from module_admin.service.seller_blacklist_service import SellerBlacklistService
from module_admin.service.login_service import LoginService
from module_admin.entity.vo.user_vo import CurrentUserModel
from utils.response_util import ResponseUtil
from utils.log_util import logger


sellerBlacklistRouter = APIRouter(prefix="/system/seller-blacklist", tags=["商家黑名单"])


@sellerBlacklistRouter.get("/list")
async def get_list(
    seller_id: str = None,
    seller_nick: str = None,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    获取商家黑名单列表（按用户隔离，管理员可查看所有用户的黑名单）
    """
    try:
        # ✅ 判断是否是管理员（role_id=1的超级管理员）
        role_id_list = [role.role_id for role in current_user.user.role]
        is_admin = 1 in role_id_list
        
        # ✅ 管理员可以查看所有用户的黑名单（不传user_id），普通用户只能查看自己的
        user_id = None if is_admin else current_user.user.user_id
        
        query_dict = {}
        if seller_id:
            query_dict['seller_id'] = seller_id
        if seller_nick:
            query_dict['seller_nick'] = seller_nick
        
        blacklist = await SellerBlacklistService.get_list(db, query_dict, user_id=user_id)
        
        # ✅ 批量获取创建者用户名（避免N+1查询）
        from module_admin.entity.do.user_do import SysUser
        from sqlalchemy import select
        
        create_by_ids = list(set([item.create_by for item in blacklist if item.create_by]))
        user_name_map = {}
        if create_by_ids:
            user_query = select(SysUser.user_id, SysUser.user_name, SysUser.nick_name).where(
                SysUser.user_id.in_(create_by_ids),
                SysUser.del_flag == '0'
            )
            user_result = await db.execute(user_query)
            for row in user_result:
                user_id_val, user_name, nick_name = row
                # 优先使用昵称，如果没有则使用用户名
                display_name = nick_name if nick_name else user_name
                user_name_map[user_id_val] = display_name
        
        result = [
            {
                'id': item.id,
                'seller_id': item.seller_id,
                'seller_nick': item.seller_nick,
                'reason': item.reason,
                'remark': item.remark,
                'status': getattr(item, 'status', '0') or '0',  # ✅ 添加status字段，默认'0'
                'create_by': item.create_by,
                'create_by_name': user_name_map.get(item.create_by, f'用户ID: {item.create_by}'),  # ✅ 添加创建者用户名
                'create_time': item.create_time.isoformat() if item.create_time else None,
                'update_time': item.update_time.isoformat() if item.update_time else None
            }
            for item in blacklist
        ]
        
        return ResponseUtil.success(data=result, dict_content={'total': len(result)})
    except Exception as e:
        logger.error(f"获取商家黑名单列表失败: {e}")
        return ResponseUtil.failure(msg=str(e))


@sellerBlacklistRouter.get("/{blacklist_id}")
async def get_by_id(
    blacklist_id: int,
    db: AsyncSession = Depends(get_db)
):
    """
    根据ID获取商家黑名单
    """
    try:
        blacklist = await SellerBlacklistService.get_by_id(db, blacklist_id)
        if not blacklist:
            return ResponseUtil.failure(msg="黑名单不存在")
        
        result = {
            'id': blacklist.id,
            'seller_id': blacklist.seller_id,
            'seller_nick': blacklist.seller_nick,
            'reason': blacklist.reason,
            'remark': blacklist.remark,
            'status': getattr(blacklist, 'status', '0') or '0',  # ✅ 添加status字段
            'create_by': blacklist.create_by,
            'create_time': blacklist.create_time.isoformat() if blacklist.create_time else None
        }
        
        return ResponseUtil.success(data=result)
    except Exception as e:
        logger.error(f"获取商家黑名单失败: {e}")
        return ResponseUtil.failure(msg=str(e))


@Log(title='添加商家黑名单', business_type=BusinessType.INSERT)
@sellerBlacklistRouter.post("")
async def add(
    request: Request,
    blacklist_data: dict,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    添加商家黑名单
    
    Body:
    {
        "seller_id": "卖家ID",
        "seller_nick": "卖家昵称",
        "reason": "拉黑原因",
        "remark": "备注"
    }
    """
    try:
        # ✅ 修复：从认证用户获取 create_by 和 dept_id
        blacklist_data['create_by'] = current_user.user.user_id
        blacklist_data['dept_id'] = current_user.user.dept_id
        
        # ✅ 添加详细日志，便于诊断
        logger.info(f"添加商家黑名单: seller_id={blacklist_data.get('seller_id')}, seller_nick={blacklist_data.get('seller_nick')}, create_by={blacklist_data.get('create_by')}, dept_id={blacklist_data.get('dept_id')}")
        
        result = await SellerBlacklistService.add(db, blacklist_data)
        
        # ✅ 刷新对象以确保所有属性都已加载（避免异步懒加载问题）
        await db.refresh(result)
        
        # ✅ 返回添加成功的记录，便于前端刷新
        return ResponseUtil.success(
            msg="添加成功",
            data={
                'id': result.id,
                'seller_id': result.seller_id,
                'seller_nick': result.seller_nick,
                'reason': result.reason,
                'create_time': result.create_time.isoformat() if result.create_time else None
            }
        )
    except ValueError as e:
        logger.warning(f"添加商家黑名单验证失败: {e}")
        return ResponseUtil.failure(msg=str(e))
    except Exception as e:
        logger.exception(f"添加商家黑名单失败: {e}")
        return ResponseUtil.failure(msg=f"添加失败: {str(e)}")


@Log(title='更新商家黑名单', business_type=BusinessType.UPDATE)
@sellerBlacklistRouter.put("/{blacklist_id}")
async def update(
    blacklist_id: int,
    update_data: dict,
    db: AsyncSession = Depends(get_db)
):
    """
    更新商家黑名单
    """
    try:
        await SellerBlacklistService.update(db, blacklist_id, update_data)
        return ResponseUtil.success(msg="更新成功")
    except Exception as e:
        logger.error(f"更新商家黑名单失败: {e}")
        return ResponseUtil.failure(msg="更新失败")


@Log(title='删除商家黑名单', business_type=BusinessType.DELETE)
@sellerBlacklistRouter.delete("/{blacklist_id}")
async def delete(
    blacklist_id: int,
    db: AsyncSession = Depends(get_db)
):
    """
    删除商家黑名单
    """
    try:
        await SellerBlacklistService.delete(db, blacklist_id)
        return ResponseUtil.success(msg="删除成功")
    except Exception as e:
        logger.error(f"删除商家黑名单失败: {e}")
        return ResponseUtil.failure(msg="删除失败")


@Log(title='批量删除商家黑名单', business_type=BusinessType.DELETE)
@sellerBlacklistRouter.delete("")
async def batch_delete(
    ids: str,
    db: AsyncSession = Depends(get_db)
):
    """
    批量删除商家黑名单
    
    Query:
        ids: 1,2,3
    """
    try:
        blacklist_ids = [int(id) for id in ids.split(',')]
        await SellerBlacklistService.batch_delete(db, blacklist_ids)
        return ResponseUtil.success(msg="删除成功")
    except Exception as e:
        logger.error(f"批量删除商家黑名单失败: {e}")
        return ResponseUtil.failure(msg="删除失败")


@Log(title='从搜索结果拉黑商家', business_type=BusinessType.INSERT)
@sellerBlacklistRouter.post("/from-search")
async def add_from_search(
    item_data: dict,
    db: AsyncSession = Depends(get_db)
):
    """
    从搜索结果直接拉黑商家
    
    Body:
    {
        "seller_id": "卖家ID",
        "seller_nick": "卖家昵称"
    }
    """
    try:
        await SellerBlacklistService.add_from_search_result(db, item_data)
        return ResponseUtil.success(msg="拉黑成功")
    except ValueError as e:
        return ResponseUtil.failure(msg=str(e))
    except Exception as e:
        logger.error(f"拉黑商家失败: {e}")
        return ResponseUtil.failure(msg="拉黑失败")

